import { useUserStore } from "@/stores/login";
import { getToken } from "@/utils/auth";
import axios from "axios";
import { ElMessage } from "element-plus";

const config = {
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 30 * 1000
};

const service = axios.create(config);

service.interceptors.request.use(
  (config) => {
    //
    const token = getToken();

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

service.interceptors.response.use(
  (response) => {
    // 这里应该有个code的值
    const { code, message } = response.data;
    if (code != 0) {
      ElMessage.error(message);
      return Promise.reject(message);
    }
    return response.data;
  },
  (err) => {
    // 这里需要考虑如果登录的token不对，进行的处理
    const res = err.response;
    if (res.status === 401) {
      // token信息不对
      const userStore = useUserStore();
      userStore.logout(); // 移除token
      window.location.reload();
    }
    return Promise.reject(err);
  }
);

export default service;
